package org.example.transaction_springboot_demo.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.annotation.MapperScans;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@MapperScans(value = {
        @MapperScan(basePackages = "org.example.transaction_springboot_demo.mapper.d1", sqlSessionFactoryRef = "d1SqlSessionFactory"),
        @MapperScan(basePackages = "org.example.transaction_springboot_demo.mapper.d2", sqlSessionFactoryRef = "d2SqlSessionFactory")
})
@Configuration
public class TransConfig {

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.d1")
    public DruidDataSource d1DataSource() {
        return new DruidDataSource();
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.d2")
    public DruidDataSource d2DataSource() {
        return new DruidDataSource();
    }

    @Bean
    public SqlSessionFactory d1SqlSessionFactory(@Qualifier("d1DataSource")DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        return sqlSessionFactoryBean.getObject();
    }

    @Bean
    public SqlSessionFactory d2SqlSessionFactory(@Qualifier("d2DataSource")DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        return sqlSessionFactoryBean.getObject();
    }
}
